visit数组不能用有多余的行 列
#include<stdio.h>
#include<string.h>
const int MAXN = 8;
int visit[MAXN][MAXN];
int dist[MAXN][MAXN];
int q[MAXN*MAXN];
int dx[8]={-2,-2,-1,-1,+1,+1,+2,+2};
int dy[8]={-1,+1,-2,+2,-2,+2,-1,+1};
int bfs(int i,int j,int ii,int jj);
int main()
{
//
freopen("input.txt","r",stdin);
char s1[5];
char s2[5];
while(scanf("%s%s",s1,s2)==2)
{
int sr = s1[1]-'1';
int sc = s1[0]-'a';
int er = s2[1]-'1';
int ec = s2[0]-'a';
memset(visit,0,sizeof(visit));
int dis = bfs(sr,sc,er,ec);
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,dis);
}
}
int bfs(int i,int j,int ii,int jj)
{
int front = 0;
int rear = 0;
int u=i*MAXN+j;
q[rear++] = u;
visit[i][j] = 1;
dist[i][j] = 0;
if(i == ii && j==jj)
return dist[i][j];
while(front<rear)
{
u = q[front++];
i = u/MAXN;
j = u%MAXN;
for(int d = 0; d < 8;d++)
{
int ni = i + dx[d];
int nj = j + dy[d];
if(ni>=0&&ni<MAXN&&nj>=0&&nj<MAXN&&!visit[ni][nj]) //此处ni,nj上限必须为实际行列数
{
q[rear++] = ni*MAXN+nj;
visit[ni][nj] = 1;
dist[ni][nj] = dist[i][j]+1;
if(ni == ii && nj==jj)
return dist[ni][nj];
}
}
}
}